<template>
  <div class="cl-chart" ref="chartDom"></div>
</template>
<script setup>
import { onMounted, watch, ref, toRaw } from 'vue'
import * as echarts from 'echarts'
import { fa } from 'element-plus/es/locales.mjs'

const props = defineProps({
  lineProps: {
    type: Object,
    default: () => {
      return {}
    }
  },
  data: {
    type: Array,
    default: () => []
  }
})
const chartDom = ref(null)
let myChart
const echartsInit = () => {
  myChart = echarts.init(chartDom.value)
}
const echartsetOption = (param1 = [], param2) => {
  let option = {
    grid: {
      show: false,
      top: '15%',
      bottom: '2%',
      left: '5%',
      right: '2%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      name: 'h',
      nameLocation: 'end',
      nameTextStyle: {
        color: '#fff',
        align: 'right'
      },
      boundaryGap: false,
      axisLine: {
        show: false,
        lineStyle: {
          color: 'red'
        }
      },
      axisTick: {
        show: false,
        alignWithLabel: true
      },
      axisLabel: {
        show: true,
        color: '#fff',
        rotate: -90
      },
      data: param1
    },
    yAxis: {
      type: 'value',
      name: props.lineProps.yAxisName,
      nameLocation: 'end',
      nameTextStyle: {
        color: '#fff',
        align: 'right'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(229, 243, 247, 0.2)'
        }
      },
      axisLabel: {
        show: true,
        color: '#fff'
      }
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    series: [
      {
        name: param2.name,
        data: param2.data,
        type: 'line',
        smooth: true,
        showSymbol: false,
        lineStyle: {
          color: props.lineProps.color
        },
        areaStyle: {
          color: props.lineProps.color,
          opacity: 0.2,
          origin: param2.min
        }
      }
    ]
  }
  if (myChart) {
    myChart.setOption(option)
  }
}
onMounted(() => {
  echartsInit()
})

watch(
  () => props.data,
  (newVal) => {
    const _newVal = toRaw(newVal)

    let xaxis = []
    let series = {
      name: '',
      data: [],
      min: 0
    }
    for (let i = 0; i < _newVal.length; i++) {
      xaxis.push(_newVal[i].recordTimeStr) // x轴数据
      if (i === 0) {
        series.name = _newVal[i].name // 系列名称
      }
      series.min = Math.min(series.min, _newVal[i].value)
      series.data.push(_newVal[i].value) // 系列数据
    }
    echartsetOption(xaxis, series)
  }
)
</script>

<style lang="scss" scoped>
.cl-chart {
  width: 100%;
  height: 100%;
}
</style>
